<script setup lang="ts">
import { ref } from 'vue';
import { ElDialog, ElMessageBox } from 'element-plus';
import { aDialogProps } from './dialog';

const props = defineProps(aDialogProps);
const emits = defineEmits(['open', 'confirm', 'close']);

const dialogVisible = ref(false);
const title = ref(props.title);

const openModel = val => {
  if (val) {
    title.value = val;
  }
  dialogVisible.value = true;
};

const handleClose = (done: () => void) => {
  ElMessageBox.confirm(props.closeMessage || 'Are you sure to close this dialog?')
    .then(() => {
      dialogVisible.value = false;
      emits('close');
    })
    .then(() => done())
    .catch(() => {
      // catch error
    });
};

const onConfirm = async () => {
  await emits('confirm');
  dialogVisible.value = false;
};

defineExpose({ openModel });
</script>
<template>
  <ElDialog
    v-bind="{ ...props }"
    :class="['rounded-lg', $attrs.class]"
    v-model="dialogVisible"
    :before-close="handleClose"
    :title="title"
  >
    <template v-if="$slots.default">
      <slot></slot>
    </template>
    <span v-else>This is a message</span>
    <template #footer>
      <span class="dialog-footer">
        <a-button v-if="showClose" @click="handleClose">Cancel</a-button>
        <a-button type="primary" @click="onConfirm">Confirm</a-button>
      </span>
    </template>
  </ElDialog>
</template>

<style lang="scss" scoped></style>
